//
//  KRHomeDataTool.m
//  cookBook
//
//  Created by kuroken on 16/2/5.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRHomeDataTool.h"
#import <FMDB.h>
#import "KRResult.h"

@implementation KRHomeDataTool

static FMDatabase *_db;
+ (void)initialize
{
    // 1、获取沙盒中数据库的路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    // 2、判断 caches 文件夹是否存在.不存在则创建
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL tag = [manager fileExistsAtPath:path isDirectory:NULL];
    
    if (!tag) {
        [manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    // 3.打开数据库
    NSString *fullPath =  [path stringByAppendingPathComponent:@"homeData.sqlite"];
    _db = [FMDatabase databaseWithPath:fullPath];
    [_db open];

    // 2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_homeData (homeData blob NOT NULL);"];
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_searchData (id integer PRIMARY KEY, searchWord text NOT NULL);"];
}

+ (void)close
{
    // 关闭数据库
    [_db close];
}

+ (NSDictionary *)results
{
    NSString *sql = @"SELECT * FROM t_homeData;";
    FMResultSet *set = [_db executeQuery:sql];
    NSDictionary *resultDict;
    while (set.next) {
        NSData *data = [set objectForColumnName:@"homeData"];
        resultDict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    return resultDict;
}

+ (void)saveHomeData:(NSDictionary *)dict
{
    // 要将一个对象存进数据库的blob字段,最好先转为NSData
    // 一个对象要遵守NSCoding协议,实现协议中相应的方法,才能转成NSData
    // NSDictionary --> NSData
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dict];
    // 删除表中所有行
    [_db executeUpdateWithFormat:@"DELETE FROM t_homeData;"];
    // 插入新数据
    [_db executeUpdateWithFormat:@"INSERT INTO t_homeData(homeData) VALUES (%@);", data];
//    [_db executeUpdateWithFormat:@"UPDATE t_homeData SET homeData = %@;", data];
}

+ (NSArray *)searchData
{
    NSString *sql = @"SELECT searchWord FROM t_searchData ORDER BY id DESC LIMIT 10;";
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *searchArray = [NSMutableArray array];
    while (set.next) {
        NSString *searchWord = [set objectForColumnName:@"searchWord"];
        [searchArray addObject:searchWord];
    }
    return searchArray;
}

+ (void)saveSearchWord:(NSString *)searchWord
{
    NSString *deleteSql = [NSString stringWithFormat:@"DELETE FROM t_searchData WHERE searchWord = '%@'", searchWord];
    [_db executeUpdate:deleteSql];

    [_db executeUpdateWithFormat:@"INSERT INTO t_searchData(searchWord) VALUES(%@);", searchWord];
}

+ (void)deleteSearchData
{
    [_db executeUpdate:@"DELETE FROM t_searchData;"];
}
@end
